﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExtensionHaversine.xaml.cs" company="">
//   
// </copyright>
// <summary>
//   Defines the ExtensionHaversine type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace devMobile.Location
{
    using System;
    using System.Device.Location;

    using devMobile.Math;

    public static class ExtensionHaversine
    {
        /// <summary>
        /// </summary>
        public const float EarthKilometersRadius = 6378.0F;

        /// <summary>
        /// </summary>
        public const float EarthMilesRadius = 3963.42F;

        /// <summary>
        /// </summary>
        /// <param name="from">
        /// The from.
        /// </param>
        /// <param name="to">
        /// The to.
        /// </param>
        /// <returns>
        /// </returns>
        public static float DistanceInMiles(this GeoCoordinate from, GeoCoordinate to)
        {
            var difLatitud = (to.Latitude - from.Latitude).ToRadians();
            var difLongitud = (to.Longitude - from.Longitude).ToRadians();

            var a = Math.Sin(difLatitud / 2).SquareOf()
                    +
                    Math.Cos(from.Latitude.ToRadians()) * Math.Cos(to.Latitude.ToRadians())
                    * Math.Sin(difLongitud / 2).SquareOf();

            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            return EarthMilesRadius * Convert.ToSingle(c);
        }
    }
}